package com.itheima.auth;

import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Component
public class MyUserDetailsServcie implements UserDetailsService {

    @Resource
    private PasswordEncoder passwordEncoder;

    private Map<String, Map<String,String>> users = new HashMap<>();

    private boolean inited = false;

    private void initUsers(){
        if(inited == false){
            Map<String,String> user1 = new HashMap<>();
            user1.put("username","user1");
            user1.put("password",passwordEncoder.encode("123456"));
            user1.put("authority","ROLE_USER1,user1,search_checkitem");

            Map<String,String> user2 = new HashMap<>();
            user2.put("username","user2");
            user2.put("password",passwordEncoder.encode("000000"));
            user2.put("authority","ROLE_USER2");

            users.put("user1",user1);
            users.put("user2",user2);
            inited = true;
        }
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        initUsers();
        Map<String,String> user = users.get(username);//模拟数据库查询
        if(user == null){
            return new User(username,"", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
        }
        return new User(username, user.get("password"),
                AuthorityUtils.commaSeparatedStringToAuthorityList(user.get("authority")));
    }

}
